package com.nowcoder.community.service;

import com.nowcoder.community.utils.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class LikeService {
    @Autowired
    private RedisTemplate redisTemplate;

    // 点赞
    public void like(int userId, int entityType, int entityId, int entityUserId){
        String entityRedisKey = RedisKeyUtil.getEntityRedisKey(entityType, entityId);
        String userLikeCountRedisKey = RedisKeyUtil.getUserLikeCountRedisKey(entityUserId);

        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                Boolean isMember = redisTemplate.opsForSet().isMember(entityRedisKey, userId);
                redisTemplate.multi(); // 查询后再开启事务
                if (isMember){
                    // 取消赞
                    redisTemplate.opsForSet().remove(entityRedisKey, userId);
                    redisTemplate.opsForValue().decrement(userLikeCountRedisKey);
                }else {
                    // 点赞
                    redisTemplate.opsForSet().add(entityRedisKey, userId);
                    redisTemplate.opsForValue().increment(userLikeCountRedisKey);
                }
                return redisTemplate.exec(); // 提交事务
            }
        });
    }

    // 统计实体的赞的数量
    public long countEntityLikes(int entityType, int entityId){
        return redisTemplate.opsForSet().size(RedisKeyUtil.getEntityRedisKey(entityType, entityId));
    }

    /**
     * 统计用户获得的赞的数量
     * */
    public int countUserLikes(int userId){
        String userLikeCountRedisKey = RedisKeyUtil.getUserLikeCountRedisKey(userId);
        Integer count = (Integer) redisTemplate.opsForValue().get(userLikeCountRedisKey);
        return count == null ? 0 : count.intValue();
    }


    /**
     * 查询用户点赞状态
     * @return int 0: 未赞，1:已赞
     */
    public int likeStatus(int userId, int entityType, int entityId){
        String redisKey = RedisKeyUtil.getEntityRedisKey(entityType, entityId);
        return redisTemplate.opsForSet().isMember(redisKey, userId) ? 1 : 0;
    }
}
